package com.usian.behavior.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.behavior.mapper.ApLikesBehaviorMapper;
import com.usian.behavior.service.ApBehaviorEntryService;
import com.usian.behavior.service.ApLikesBehaviorService;
import com.usian.model.behavior.dtos.LikesBehaviorDto;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.behavior.pojos.ApLikesBehavior;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApLikesBehaviorServiceImpl extends ServiceImpl<ApLikesBehaviorMapper, ApLikesBehavior> implements ApLikesBehaviorService {
    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;

    @Override
    public ResponseResult likeOrNoLike(LikesBehaviorDto dto) {
        //判断参数
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询行为实体
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdAndEquipmentId(AppThreadLocalUtils.getUser().getId(), dto.getEquipmentId());
        if (apBehaviorEntry==null){
            return ResponseResult.errorResult(502,"行为实体不存在");
        }
        //查询ap_likes_behavior表中的数据
        ApLikesBehavior apLikesBehavior = getOne(Wrappers.<ApLikesBehavior>lambdaQuery().eq(ApLikesBehavior::getEntryId, apBehaviorEntry.getId()).eq(ApLikesBehavior::getArticleId, dto.getArticleId()));
        if (apLikesBehavior==null){
            ApLikesBehavior likesBehavior = new ApLikesBehavior();
            likesBehavior.setArticleId(dto.getArticleId());
            likesBehavior.setCreatedTime(new Date());
            likesBehavior.setEntryId(apBehaviorEntry.getId());
            likesBehavior.setType(dto.getType());
            likesBehavior.setOperation(dto.getOperation());
            save(likesBehavior);
        }else {
            apLikesBehavior.setOperation(dto.getOperation());
            apLikesBehavior.setCreatedTime(new Date());
            updateById(apLikesBehavior);
            //LambdaUpdateWrapper<ApLikesBehavior> updateWrapper = new LambdaUpdateWrapper<>();
            //updateWrapper.eq(ApLikesBehavior::getEntryId,apBehaviorEntry.getId()).eq(ApLikesBehavior::getArticleId,dto.getArticleId());
            //updateWrapper.set(ApLikesBehavior::getOperation,dto.getOperation());
            //update(updateWrapper);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
